package tpdisenio2009.mvp.presenter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import tpdisenio2009.Constants;
import tpdisenio2009.Tpdisenio2009App;
import tpdisenio2009.model.beans.FantasyTeam;
import tpdisenio2009.model.beans.FantasyTeamTransferByTournamentDate;
import tpdisenio2009.model.beans.SoccerPlayer;
import tpdisenio2009.model.beans.TournamentDate;
import tpdisenio2009.model.beans.User;
import tpdisenio2009.mvp.display.QueryAFAPlayersViewImpl;
import tpdisenio2009.mvp.display.UpdateFantasyTeamView2;
import tpdisenio2009.services.FantasyTeamPlayerService;
import tpdisenio2009.services.FantasyTeamService;
import tpdisenio2009.services.TournamentDateService;

/**
 *
 * @author Nicolás Galliano
 */
public class UpdateFantasyTeamPresenter2 extends DefaultPresenter<UpdateFantasyTeamView2> {

    private final FantasyTeamService ftservice;
    private final FantasyTeamPlayerService ftpservice;    
    private final TournamentDateService tournamentDateService;

    private ActionListener queryPlayersListener;
    private ActionListener savePlayersListener;
    private ActionListener exitPlayersListener;

    private int changesCount = 0;
    private List<SoccerPlayer> oldPlayers = new LinkedList<SoccerPlayer>();
    private List<SoccerPlayer> newLineUpPlayers = new LinkedList<SoccerPlayer>();
    private List<SoccerPlayer> newSubstitutePlayers = new LinkedList<SoccerPlayer>();

    public UpdateFantasyTeamPresenter2(UpdateFantasyTeamView2 view) {
        super(view);

        ftservice = new FantasyTeamService();
        ftpservice = new FantasyTeamPlayerService();        
        tournamentDateService = new TournamentDateService();

        getView().setFantasyTeamName( ((User)Tpdisenio2009App.loggedUser).getFantasyTeam().getName() );
                
        FantasyTeam team = ((User) Tpdisenio2009App.loggedUser).getFantasyTeam();
        TournamentDate date = tournamentDateService.getFirstOpenTournamentDate();
        getView().loadPlayers( ftpservice.getFantasyTeamPlayersByDate( team, date ) );
        getView().setLLevasGastado( getFantasyTeamCotization() );
        getView().setTeQuedan( Constants.TOTAL_MONEY - getFantasyTeamCotization() );
        
        //changesCount = ftservice.getTransfersCountInCurrentDate( (User) Tpdisenio2009App.loggedUser );
        changesCount = ftservice.getTransfersCountInCurrentDate( (User) Tpdisenio2009App.loggedUser );        
        //changesCount = ftservice.getChangesCountInCurrentDate( (User) Tpdisenio2009App.loggedUser );

        bind();
    }

    public int getFantasyTeamCotization() {
        int cotization = 0;

        List<SoccerPlayer> soccerPlayers = getView().getSoccerPlayers();
        for (SoccerPlayer player : soccerPlayers)
            cotization += player.getPrice();

        return cotization;
    }

    public void bind() {        
        queryPlayersListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TournamentDate date = tournamentDateService.getFirstOpenTournamentDate();
                if (date.getBanDate() != null && date.getBanDate().before( new Date() )) {
                    getView().showError( "No es posible realizar modificaciones en el equipo durante el período de veda.", "Transferencia invalida..." );
                    return;
                }

                String position = null;
                SoccerPlayer soccerPlayer = null;
                int index = getView().getSelectedPosition();

                if (index >= 0) {
                    soccerPlayer = getView().getPlayerAtPosition( index );

                    if (index == 0 || index == 11)
                        position = SoccerPlayer.GOALKEEPER_POSITION;
                    else if (index > 0 && index < 5 || index == 12)
                        position = SoccerPlayer.DEFENDER_POSITION;
                    else if (index > 4 && index < 8 || index == 13)
                        position = SoccerPlayer.MIDFIELDER_POSITION;
                    else if (index > 7 && index < 11 || index == 14)
                        position = SoccerPlayer.FORWARD_POSITION;
                    else
                        index = -1;
                }

                if (index < 0) {
                    getView().showError( "Por favor, seleccione el jugador a reemplazar.", "Efectuando traspaso..." );
                    return;
                }

                int cotization = getFantasyTeamCotization();

                List<SoccerPlayer> tempPlayers = new LinkedList<SoccerPlayer>( getView().getSoccerPlayers() );
                if ( soccerPlayer != null )
                    tempPlayers.remove( soccerPlayer );

                if (changesCount >= 3) {
                    getView().showError( "Ya se han realizado los 3 cambios permitidos para esta fecha", "Límite de cambios superado");
                    return;
                }

                QueryAFAPlayersViewImpl queryPlayersView = new QueryAFAPlayersViewImpl( null, true, position, Constants.TOTAL_MONEY - cotization + (soccerPlayer==null? 0 : soccerPlayer.getPrice()), tempPlayers );
                QueryAFAPlayersPresenter queryPlayersPresenter = new QueryAFAPlayersPresenter( queryPlayersView );
                queryPlayersPresenter.getView().asWidget().setVisible( true );

                SoccerPlayer player = queryPlayersPresenter.getSelectedPlayer();

                FantasyTeam team = ((User) Tpdisenio2009App.loggedUser).getFantasyTeam();
                if( ftpservice.existsCurrentPlayerInFantasyTeam( team , date, player) ) {
                    getView().showError( "El jugador que intenta agregar ya pertence a su equipo", "Transferecia inválida");
                    return;
                }

                if (player != null) {
                    changesCount++;

                    if ( index < 11 ) {
                        newLineUpPlayers.add( player );
                    } else {
                        newSubstitutePlayers.add(player);
                    }
                    
                    //changesCount = ftservice.getChangesCountInCurrentDate( (User) Tpdisenio2009App.loggedUser );
                    //changesCount = ftservice.getTransfersCountInCurrentDate( (User) Tpdisenio2009App.loggedUser );

                    if (soccerPlayer != null)
                        oldPlayers.add( soccerPlayer );
                    getView().setPlayerAtPosition( index, player );                    

                    cotization = getFantasyTeamCotization();
                    getView().setLLevasGastado( cotization );
                    getView().setTeQuedan( Constants.TOTAL_MONEY - cotization );
                }
            }
        };
        getView().addQueryPlayersListener(queryPlayersListener);

        savePlayersListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if( showConfirmation( "¿Confirma que desea guardar los cambios?" ) ) {
                    for (SoccerPlayer player : oldPlayers)
                        ftpservice.setEndDate(player);

                    ftpservice.updateLineUpPlayers( newLineUpPlayers );
                    ftpservice.updateSubstitutePlayers( newSubstitutePlayers );

                    TournamentDate date = tournamentDateService.getFirstOpenTournamentDate();
                    FantasyTeam team = ((User) Tpdisenio2009App.loggedUser).getFantasyTeam();

                    if ( ftservice.existFantasyTeamTransferByTournamentDate(team, date) ) {
                        FantasyTeamTransferByTournamentDate transfer = ftservice.getFantasyTeamTransferByTournamentDate(team, date);
                        ftservice.updateTransfer(transfer, changesCount);
                    } else {
                        ftservice.createFantasyTeamTransferByTournamentDate(team, date, changesCount);
                    }

                    //List<SoccerPlayer> players = getView().getSoccerPlayers();
                    //ftpservice.updatePlayers( players );
                    getView().showNotification( "<html>¡Felicitaciones! Su equipo ha sido<br>modficado correctamente.</html>", "Equipo creado" );
                    getView().close();
                }
            }
        };
        getView().addSaveListener(savePlayersListener);

        exitPlayersListener = new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if( showConfirmation( "<html>¿Está seguro que desea salir?<br>Perderá la información no guardada" ) ) {
                    getView().close();
                }
            }
        };
        getView().addExitListener(exitPlayersListener);
    }

    public void unbind() {
        if (queryPlayersListener != null) {
            getView().removeQueryPlayersListener(queryPlayersListener);
        }
        if (savePlayersListener != null) {
            getView().removeSaveListener(savePlayersListener);
        }
        if (exitPlayersListener != null) {
            getView().removeExitListener(exitPlayersListener);
        }
    }

    private boolean showConfirmation(String message) {
        return getView().showConfirmation( message );
    }
}
